import defaultSettings from '@/settings'
import { toast } from "@/utils/utils";
import navMenuService from '@/services/navmenu/NavMenuService'

export default {
    namespaced: true,
    state() {
        return {
            // 标签导航
            menus: [],
            // 左侧菜单
            menuList: [],
            isCollapse: false,
            cpath: "",
            slideWidth: "180px"
        }
    },
    mutations: {

        handleSlideWidth(state) {
            state.slideWidth = state.slideWidth == "208px" ? "64px" : "208px";
            state.isCollapse = state.slideWidth == "64px";
        },

        // 添加菜单
        addMenu(state, payload) {
            // 1： 根据你路径查找是否在数组，中
            var index = state.menus.findIndex(s => s.path == payload.path);
            // 2: 如果不在index = -1 ，追加到数组中
            if (index == -1) {
                state.menus.map(menu => menu.active = false);
                // 3 :添加进去即可
                state.menus.push(payload);
                // 4: 打开的最大数量 超过defaultSettings.menucount = 10个
                const mlen = state.menus.length;
                if (mlen > defaultSettings.menucount) {
                    // 5: 数组首位弹出 pop() 末尾弹出 shift() 首位弹出
                    state.menus.shift();
                }
            }
        },

        // 关闭菜单
        closeMenu(state, index) {
            var active = state.menus[index].active;
            if (!active) {
                state.menus.splice(index, 1);
            } else {
                toast("关闭未选中的节点");
            }
        },

        // 清除菜单
        clearMenu(state) {
            state.menus = [];
        },

        // 添加菜单
        addMenuList(state, menuList) {
            state.menuList = menuList;
        },

        // 设置当前路由
        addPath(state, currentPath) {
            state.cpath = currentPath;
        },

    },
    actions: {
        async asyncGetMenuList({ commit }) {
            var serverResponse = await navMenuService.getMenuList();
            commit("addMenuList", serverResponse.data)
            return serverResponse.data;
        }

    },
    getters: {

        menuLen(state) {
            return state.menus.length;
        },

        cpath(state) {
            return state.cpath
        }
    }
}